package com.gucheng.ggbi.bizmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class BiInitMain {

    public static void main(String[] args) {
        try {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("localhost");
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();
            String exchangeName = BiMqConstant.BI_EXCHANGE_NAME;

            // 先尝试删除可能已存在的交换器和队列
            try {
                channel.exchangeDelete(exchangeName);
                String queueName = BiMqConstant.BI_QUEUE_NAME;
                channel.queueDelete(queueName);
            } catch (Exception e) {
                // 如果删除失败，可能是因为它们不存在，忽略这个错误
                log.warn("Failed to delete exchange or queue. Maybe they don't exist. Error: {}", e.getMessage());
            }

            // 声明普通交换器
            channel.exchangeDeclare(exchangeName, "direct", true);

            // 声明普通队列并设置死信交换器等参数
            Map<String, Object> argsQueue = new HashMap<>();
            String queueName = BiMqConstant.BI_QUEUE_NAME;
            argsQueue.put("x-dead-letter-exchange", DeadLetterQueueConfig.BI_DEAD_LETTER_EXCHANGE_NAME);
            argsQueue.put("x-dead-letter-routing-key", "bi_dead_routing_key");
            channel.queueDeclare(queueName, true, false, false, argsQueue);
            channel.queueBind(queueName, exchangeName, BiMqConstant.BI_ROUTING_KEY);

            // 声明死信交换器和队列
            String deadLetterExchangeName = DeadLetterQueueConfig.BI_DEAD_LETTER_EXCHANGE_NAME;
            channel.exchangeDeclare(deadLetterExchangeName, "direct", true);
            String deadLetterQueueName = DeadLetterQueueConfig.BI_DEAD_LETTER_QUEUE_NAME;
            channel.queueDeclare(deadLetterQueueName, true, false, false, null);
            channel.queueBind(deadLetterQueueName, deadLetterExchangeName, "bi_dead_routing_key");
        } catch (Exception e) {
            log.error("Error initializing RabbitMQ setup", e);
        }
    }
}